<template>
	<view class="container">
		<!-- 顶部导航栏 -->
		<view class="header">
			<text class="header-title">服用药物</text>
		</view>

		<!-- 无限下拉框数据展示 -->
		<scroll-view class="medication-scroll-view" scroll-y @scrolltolower="loadMoreData">
			<block v-if="medicationList.length > 0">
				<view class="medication-item" v-for="(item, index) in medicationList" :key="item.id" @click="editMedication(item)">
					<!-- 已移除图片相关标签 -->
					<view class="item-content">
						<text class="medication-name">{{ item.medicationName }}</text>
						<!-- 可根据需要添加更多信息 -->
						<text class="dosage-info">当前用法：{{ item.currentDosageUsage }}</text>
						<text class="dosage-info">剩余药量：{{ item.currentStockAmount }}</text>
					</view>
					<view class="delete-button-wrapper" @click.stop="confirmDelete(item.recordId)">
						<button class="delete-button">删除</button>
					</view>
				</view>
				<!-- 自定义加载更多提示 -->
				<view v-if="loadingMore" class="load-more-text">
					<text>正在加载...</text>
				</view>
				<view v-else-if="!hasMore && medicationList.length > 0" class="load-more-text">
					<text>没有更多数据了</text>
				</view>
			</block>
			<view v-else class="empty-data-hint">
				<text>你没有添加任何服用的药物信息</text>
			</view>
		</scroll-view>

		<!-- 底部添加处方按钮 -->
		<view class="footer-button-wrapper">
			<button class="add-prescription-button" @click="navigateToAddMedication">添加处方</button>
		</view>

		<!-- 自定义确认删除弹窗 -->
		<view class="custom-popup" v-if="showDeleteConfirm">
			<view class="custom-popup-mask" @click="cancelDelete"></view>
			<view class="custom-popup-dialog">
				<view class="dialog-title">提示</view>
				<view class="dialog-content">确定要删除这条药物信息吗？</view>
				<view class="dialog-buttons">
					<button class="dialog-button cancel-button" @click="cancelDelete">取消</button>
					<button class="dialog-button confirm-button" @click="deleteMedication">确认</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import config from '../../config.js';
	export default {
		data() {
			return {
				medicationList: [],
				page: 0,
				pageSize: 10,
				hasMore: true, // 是否还有更多数据
				loadingMore: false, // 是否正在加载更多
				deleteItemId: null, // 待删除的药物ID
				showDeleteConfirm: false, // 控制自定义删除弹窗显示隐藏
				// 已移除图片路径硬编码配置
			};
		},
		onLoad() {
			this.loadMedicationData();
		},
		onShow() {
			this.resetAndLoadData();
		},
		methods: {
			resetAndLoadData() {
				this.page = 0;
				this.medicationList = [];
				this.hasMore = true;
				this.loadMedicationData();
			},
			async loadMedicationData() {
				if (!this.hasMore || this.loadingMore) return;

				this.loadingMore = true;
				uni.showLoading({
					title: '加载中...'
				});
				// 网络请求
				const hospitalNumber = uni.getStorageSync('hospitalNumber');
				await uni.request({
				  url: `${config.baseUrl}/puwai/getMedicineInfo`,
				  method: 'GET',
				  data: {
				    hospitalNumber: hospitalNumber,
					page:this.page,
					pageSize:this.pageSize
				  },
						header: {
				    'Content-Type': 'application/json',
				    'Authorization': uni.getStorageSync('token') || ''
				  },
				  success: (res) => {
				    if (res.data && res.data.code === 1) {
				      let newData = res.data.data;
					  this.medicationList = [...this.medicationList, ...newData];
					  this.page++;
					  this.loadingMore = false;
					  uni.hideLoading();
					  
					  if (newData.length < this.pageSize) {
					  	this.hasMore = false;
					  }
				    } else {
				      uni.showToast({
				        title: res.data.msg || '获取服用药物失败',
				        icon: 'none'
				      });
				    }
				  },
				  fail: (err) => {
				    console.error('获取服用药物失败:', err);
				    uni.showToast({
				      title: '获取服用药物失败',
				      icon: 'none'
				    });
				  }
				});
			},
			loadMoreData() {
				if (this.hasMore && !this.loadingMore) {
					this.loadMedicationData();
				}
			},
			editMedication(item) {
				uni.navigateTo({
					url: `/pages/setMedicine/editMedicine?recordId=${item.recordId}&medicationName=${item.medicationName}&commonDosageUsage=${item.commonDosageUsage}&medicationNotes=${item.medicationNotes}&currentDosageUsage=${item.currentDosageUsage}&currentStockAmount=${item.currentStockAmount}`
				});
			},
			confirmDelete(id) {
				this.deleteItemId = id;
				this.showDeleteConfirm = true; // 显示自定义弹窗
			},
			cancelDelete() {
				this.showDeleteConfirm = false; // 隐藏自定义弹窗
				this.deleteItemId = null;
			},
			async deleteMedication() {
				console.log('确认删除药物ID:', this.deleteItemId);
				const formData = {
					recordId:this.deleteItemId
				}
				await uni.request({
				  url: `${config.baseUrl}/puwai/deleteMedicineInfo`,
				  method: 'POST',
				  data: formData,
				  header: {
				    'Content-Type': 'application/json',
				    'Authorization': uni.getStorageSync('token') || ''
				  },
				  success: (res) => {
				    if (res.data && res.data.code === 1) {
				      uni.showToast({
				        title: '成功删除服用药品',
				        icon: 'success'
				      });
				      
				    } else {
				      uni.showToast({
				        title: res.data.msg || '删除失败',
				        icon: 'none'
				      });
				    }
				  },
				  fail: (err) => {
				    console.error('删除服用药品失败:', err);
				    uni.showToast({
				      title: '删除失败',
				      icon: 'none'
				    });
				  }
				});
				this.medicationList = this.medicationList.filter(item => item.recordId !== this.deleteItemId);
				this.deleteItemId = null;
				this.showDeleteConfirm = false; // 关闭弹窗

				if (this.medicationList.length === 0 && this.page === 0) {
					this.hasMore = false;
				}
			},
			navigateToAddMedication() {
				console.log('跳转到添加处方页面');
				uni.navigateTo({
					url: '/pages/setMedicine/addMedicine'
				});
			}
		}
	};
</script>

<style lang="scss">
	.container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f8f8f8;
	}

	.header {
		background-color: #007aff;
		color: #ffffff;
		height: 44px;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 18px;
		font-weight: bold;
		position: sticky;
		top: 0;
		z-index: 10;
	}

	.medication-scroll-view {
		flex: 1;
		overflow-y: auto;
		padding: 10px;
		box-sizing: border-box;
	}

	.medication-item {
		position: relative;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 15px;
		margin-bottom: 10px;
		border-radius: 8px;
		min-height: 80px;
		background-color: #ffffff; /* 增加白色背景，替代原有图片背景 */
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05); /* 增加轻微阴影提升质感 */
	}

	/* 已移除图片相关样式 */

	.item-content {
		flex: 1;
		display: flex;
		flex-direction: column;
		color: #333;
	}

	.medication-name {
		font-size: 16px;
		font-weight: bold;
		margin-bottom: 5px; /* 增加与下方信息的间距 */
	}

	.dosage-info {
		font-size: 14px;
		color: #666;
		margin-top: 3px;
	}

	.delete-button-wrapper {
		margin-left: 15px;
	}

	.delete-button {
		background-color: #ff4d4f;
		color: #fff;
		font-size: 14px;
		padding: 5px 10px;
		border-radius: 5px;
		line-height: 1.5;
		margin: 0;
	}

	.empty-data-hint {
		text-align: center;
		padding: 50px 0;
		color: #999;
		font-size: 16px;
	}

	/* 自定义加载更多提示样式 */
	.load-more-text {
		text-align: center;
		padding: 15px 0;
		color: #999;
		font-size: 14px;
	}

	.footer-button-wrapper {
		padding: 10px;
		background-color: #fff;
		border-top: 1px solid #eee;
		position: sticky;
		bottom: 0;
		z-index: 10;
	}

	.add-prescription-button {
		background-color: #007aff;
		color: #ffffff;
		font-size: 16px;
		padding: 12px 0;
		border-radius: 8px;
	}

	/* 自定义弹窗样式 */
	.custom-popup {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 999;
	}

	.custom-popup-mask {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.5);
	}

	.custom-popup-dialog {
		background-color: #fff;
		border-radius: 10px;
		width: 80%;
		max-width: 300px;
		padding: 20px;
		box-sizing: border-box;
		text-align: center;
		position: relative;
		z-index: 1000;
	}

	.dialog-title {
		font-size: 18px;
		font-weight: bold;
		margin-bottom: 15px;
		color: #333;
	}

	.dialog-content {
		font-size: 16px;
		color: #666;
		margin-bottom: 25px;
		line-height: 1.5;
	}

	.dialog-buttons {
		display: flex;
		justify-content: space-around;
	}

	.dialog-button {
		flex: 1;
		margin: 0 5px;
		padding: 8px 15px;
		border-radius: 5px;
		font-size: 15px;
		line-height: 1.5;
	}

	.cancel-button {
		background-color: #e0e0e0;
		color: #333;
	}

	.confirm-button {
		background-color: #007aff;
		color: #fff;
	}
</style>